package com.xiliu.server.modules.wxmsg.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import com.alibaba.fastjson2.JSONObject;
import com.xiliu.server.modules.wxmsg.entity.XlWxApiLog;
import com.xiliu.server.modules.wxmsg.service.IXlWxApiLogService;
import com.xiliu.server.modules.wxmsg.service.IXlWxTemplateMsgService;
import com.xiliu.server.modules.wxmsg.service.SendTemplateMsgService;
import com.xiliu.server.modules.wxmsg.vo.WxMsgVo;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author xiliu
 * @description 发送订阅消息服务实现类
 * @date 2023/1/4
 */
@Service
public class SendTemplateMsgServiceImpl implements SendTemplateMsgService {

    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private IXlWxApiLogService wxApiLogService;
    @Autowired
    private IXlWxTemplateMsgService wxTemplateMsgService;

    @Override
    public WxMaSubscribeMessage convertMessageData(WxMsgVo wxMsgVo) {
        WxMaSubscribeMessage subscribeMessage = WxMaSubscribeMessage.builder()
                //这里添加的是推送消息的目标对象openId
                .toUser(wxMsgVo.getTouser())
                //这里填写的就是在后台申请添加的模板ID
                .templateId(wxMsgVo.getTemplateId())
                //添加跳转链接，如果目标用户点击了推送的消息，则会跳转到小程序主页
                .page(wxMsgVo.getPage())
                .build();
        // 添加模板数据
        JSONObject jsonObject = JSONObject.parseObject(wxMsgVo.getData());
        subscribeMessage.addData(new WxMaSubscribeMessage.MsgData("thing2", jsonObject.getString("thing2")))
                .addData(new WxMaSubscribeMessage.MsgData("thing4", jsonObject.getString("thing4")))
                .addData(new WxMaSubscribeMessage.MsgData("time3", jsonObject.getString("time3")))
                .addData(new WxMaSubscribeMessage.MsgData("thing6", jsonObject.getString("thing6")));
        return subscribeMessage;
    }

    @Override
    public void sendWxappTemplate(WxMaSubscribeMessage message) {
        XlWxApiLog wxApiLog = new XlWxApiLog();
        wxApiLog.setTime(new Date());
        wxApiLog.setData(JSONObject.toJSONString(message));
        try {
            wxMaService.getMsgService().sendSubscribeMsg(message);
            wxApiLog.setStatus(1);
        } catch (WxErrorException e) {
            e.printStackTrace();
            wxApiLog.setStatus(2);
            wxApiLog.setResult(e.getMessage());
        }
        wxApiLogService.save(wxApiLog);
    }

    @Override
    public void sendWxappTemplate(WxMsgVo wxMsgVo) {
        this.sendWxappTemplate(convertMessageData(wxMsgVo));
    }

}
